let express = require('express');
// require('express-di');
let path = require('path');
let app = module.exports = express();
let ejs = require('ejs');
// let cors = require('cors');
let config = require('config');
let cookieParser = require('cookie-parser');
let connect_mongo = require('connect-mongo');
let session = require('express-session');
let favicon = require('serve-favicon');
let bodyParser = require('body-parser');
let sessionUtils = require('./utils/sessionUtils');

let domain = require('express-domain-middleware');
app.use(domain);
require('date-format-lite');

app.use(bodyParser.json({limit: '100mb'}));
// router.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({extended: true, limit: '100mb'}));
app.use(cookieParser());

// log4js init
// require('./log4js/initLog4js');
// let log4js = require('log4js');
// let logger = log4js.getLogger(__filename);
// logger.debug('test');
let MongoStore = connect_mongo(session);

// access control
app.use(require('./intercept/accessControlIntercept'));

app.use(require('morgan')('dev'));

app.use(favicon(__dirname + '/public/favicon.ico'));

// view
app.engine('html', ejs.renderFile);
// router.engine('html', ejs.__express);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.use('/admin', express.static(path.join(__dirname, 'public')));
// app.use(log4js.connectLogger(log4js.getLogger("http"), {level: 'auto'}));

// init
require('./init');

process.argv.NODE_APP_INSTANCE = 0;
// init session
let sessionStore = global.sessionStore = new MongoStore({
    mongooseConnection: mongoose.connection,
    ttl: sessionUtils.adminSessionTTL
});

let sessionOption = global.sessionOption = {
    secret: sessionUtils.sessionSecret,
    resave: true,
    saveUninitialized: true,
    cookie: {
        // secure:true, // if set secure true, there is no cookie in response.
        maxAge: sessionUtils.adminSessionTTL,
        domain: 'http://localhost:63342/',
        httpOnly: false,
    },
    name: 'adminSession',
    httpOnly: false,
    store: sessionStore
};
app.use(session(sessionOption));
// login intercept
app.use(require('./intercept/authLoginIntercept'));
// admin router
let adminRouter = express.Router();
adminRouter.use(domain);
require('./routes')(adminRouter, null);
app.use('/bookserver', adminRouter);

// catch 404 and forward to error handler
adminRouter.use(function (req, res, next) {
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers
// error handler
// development error handler
// will print stacktrace
if (app.get('env') === 'development' || app.get('env') === 'test') {
    app.use(devErrCatchFunction);
    adminRouter.use(devErrCatchFunction);
} else {
    // production error handler
    app.use(productionErrCatchFunction);
    adminRouter.use(productionErrCatchFunction);
}

console.log('listen -- ' + (process.env.PORT || config.port));

if (app.get('env') !== 'test') {
    // app.set('env', 'test');
    app.listen(process.env.PORT || config.port);
}

function devErrCatchFunction(err, req, res, next) {
    res.status(err.status || 500);
    // console.log('error on request %d %s %s', process.domain.id, req.method, req.url);
    // console.log(err.stack);
    // logger.error('url -- ' + req.originalUrl);
    // logger.error(err.message || (err.err && err.err.message) || JSON.stringify(err.errinfo) || JSON.stringify(err));
    console.trace();
    // res.render('error', err).json(err);
    res.json(err);
}

function productionErrCatchFunction(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.errmsg,
        error: {}
    });
}
